<template>
  <div class="app-product-list">
    <div class="content">
      <van-pull-refresh>
        <van-list v-model:loading="loading" :finished="finished" :finished-text="productList.length ? '没有更多了' : '搜索想要的商品'" @load="onLoad" @offset="10">
          <template v-if="productList.length">
            <div v-for="item in productList" :key="item.id" class="product-item" @click="toDetail(item)">
              <div class="product-info">
                <p class="name">{{ item.product_name }}</p>
              </div>
            </div>
          </template>
        </van-list>
      </van-pull-refresh>
    </div>
  </div>
</template>

<script>
import { toRefs, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { fetchCategoriesById } from '@/api'
import './index.scss'

export default {
  name: 'Product',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const state = reactive({
      list: [],
      productList: [],
      loading: false,
      finished: false
    })

    onMounted(async () => {
      const { data } = await fetchCategoriesById(route.query.id)

      if (!data) {
        state.productList = []
        return
      }

      state.productList = data
    })

    const toDetail = (item) => {
      router.push({ path: `/product/${item.goodsId}` })
    }

    return {
      ...toRefs(state),
      toDetail
    }
  }
}
</script>

<style lang="scss"></style>
